import request from '@/config/axios'
import { ElMessage, ElLoading } from 'element-plus'
import {blobValidate} from '@/utils/index'
import { saveAs } from 'file-saver'
import errorCode from '@/utils/errorCode'

// 获取所有字典
export const getDictApi = (): Promise<IResponse> => {
  return request.get({ url: '/dict/list' })
}

// 模拟获取某个字典
export const getDictOneApi = async (): Promise<IResponse> => {
  return request.get({ url: '/dict/one' })
}

export const download = async (url: string, filename: string) => {
  const downloadLoadingInstance = ElLoading.service({ text: "正在下载，请稍候...", background: "rgba(0, 0, 0, 0.7)", })
  
  request.get({ url, responseType: 'blob' }).then(async res => {
    const data = res
    const isLogin = await blobValidate(data);
    if (isLogin) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      ElMessage.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    ElMessage.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close();
  });
}
export const downloadStatic = async (url: string, filename: string) => {
  const a = document.createElement("a");
  a.href = url;
  a.target = '_blank';
  a.download = filename;
  a.click();
  document.removeChild(a);
}